package com.community.controller;

import com.community.entity.Right;
import com.community.entity.Role;
import com.community.entity.User;
import com.community.service.RoleService;
import com.community.service.UserService;
import com.community.util.Constants;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;

import javax.mail.Authenticator;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.Properties;

/**
 * (User)表控制层 登入
 *
 * @author xn
 * @since 2021-09-27 16:45:30
 */
@Controller
public class LoginController {

    @Autowired
    UserService userService;
    @Autowired
    RoleService roleService;

    @PostMapping(value = "/dologin")
    public String login(Model model, HttpSession session, String account, String password) {//throws ParseException
        try {
            UsernamePasswordToken token = new UsernamePasswordToken(account, password);
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);//认证、登录

            //认证(登录)成功
            User user = (User) subject.getPrincipal();

            Role role = user.getRole(); //如果一对多关联不是立即加载，则需要通过用户获取角色
            List<Right> rights = roleService.findRightsByRole(role);
            role.getRights().addAll(rights);

            session.setAttribute(Constants.USER_SESSION, user);
            return "redirect:/index";//建议重定向
        } catch (UnknownAccountException | IncorrectCredentialsException e) {
            model.addAttribute(Constants.SYS_MESSAGE, "用户名或密码错误，登录失败！");
            return "login2";
        } catch (LockedAccountException e) {
            model.addAttribute(Constants.SYS_MESSAGE, "用户被禁用，登录失败！");
            return "login2";
        } catch (AuthenticationException e) {
            model.addAttribute(Constants.SYS_MESSAGE, "认证异常，登录失败！");
            return "login2";
        }

    }

    @RequestMapping(value = "/index2")
    public String main() {
        return "index";
    }

    @RequestMapping(value = "login")
    public String login() {
        return "/login";
    }

    @GetMapping(value = "login2")
    public String login2() {
        return "/login2";
    }

    @RequestMapping(value = "/logout")
    public String logout(HttpSession session) {
        session.removeAttribute(Constants.USER_SESSION);
        SecurityUtils.getSubject().logout();//Shiro 注销
        return "redirect:/login";//建议重定向，保证删除 Cookie
    }

    @RequestMapping(value = "/index")
    public String index() {
        return "/index";
    }

    @RequestMapping(value = "/email")
    @ResponseBody
    public int email(HttpServletRequest request) {
        String email = request.getParameter("email");
        String from = "3040088904@qq.com";
        String host = "smtp.qq.com";
        Properties properties = System.getProperties();
        properties.setProperty("mail.smtp.host", host);

        properties.setProperty("mail.smtp.port", "587");
        properties.setProperty("mail.smtp.socketFactory.port", "587");

        properties.put("mail.smtp.auth", "true");
        final long l = System.currentTimeMillis();
        final int i = (int) (l % 999999);
        int you = i;
        Session session = Session.getInstance(properties,
                new Authenticator() {
                    public PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication("3040088904@qq.com",
                                "cyptvnacojfudgbb");
                    }
                });
        try {
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
            message.setSubject("This is the Subject Line!");
            message.setText("【科泰教育】验证码:" + you + ",该验证码只在60秒内有效,失效后请重新点击发送!");
            Transport.send(message);
            System.out.println("【科泰教育】验证码:" + you + ",该验证码只在60秒内有效,失效后请重新点击发送!");
        } catch (MessagingException mex) {
            mex.printStackTrace();
        }
        return i;
    }

    @RequestMapping(value = "/register")
    @ResponseBody
    public int register(@RequestParam("yzm") String yzm) {
        System.out.println("yzm----------:" + yzm);
        Jedis jedis = new Jedis("127.0.0.1", 6379);
        jedis.set("name", yzm);
        jedis.expire("name", 60);
        Long time = jedis.ttl("name");
        int count = time.intValue();
        return count;
    }

    @RequestMapping(value = "/getrediskey")
    @ResponseBody
    public String getrediskey() {
        Jedis jedis = new Jedis("127.0.0.1", 6379);
        System.out.println("LoginController.getrediskey");
        System.out.println(jedis.get("name"));
        return jedis.get("name");
    }

    @RequestMapping(value = "/account")
    @ResponseBody
    public boolean account(User user) {
        user.setCreatedDate(new Date());
        boolean add = userService.save(user);
        return add;
    }

}